package org.zerg.service.impl;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.zerg.dao.UserDao;
import org.zerg.dao.cache.RedisTokenDao;
import org.zerg.dto.Token;
import org.zerg.entity.User;
import org.zerg.exception.TokenException;
import org.zerg.service.UserTokenService;
import org.zerg.utils.SendHttp;
import org.zerg.utils.Utils;

@Service
public class UserTokenServiceImpl extends BaseServiceImpl implements UserTokenService {

	@Value("${app_id}")
	private String app_id;

	@Value("${app_secret}")
	private String app_secret;

	@Value("${login_url}")
	private String login_url;

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private RedisTokenDao redisTokenDao;

	public Token getUserToken(String code) {
		
		Utils utils = new Utils();
		
		String params[] = { app_id, app_secret, code };
		String TokenUrl = MessageFormat.format(login_url, params);
		SendHttp sh = new SendHttp();
		String result = sh.httpRequest(TokenUrl, "GET");
		if (result == null) {
			throw new TokenException("无效");
		}
		if(isErrcode(result).equals("errcode")){
			Token token = new Token("401");
			 return token;
		}else{
			//截取openID--用户唯一标识
			String openid = this.getOpenId(result);
			//检测是否已有该用户信息
	        User user = userDao.getUserByOpenid(openid);
	        String time = this.getNowTime();
	        String retime = this.getRandomTime();
	        int times = Integer.parseInt(time);
	        //获取md5码为token----openid+时间加密
	        String to = utils.getMd5(openid+retime);
	        if(user!=null){
	        	//如果有修改其登录时间
	         userDao.updataUser(openid, times, to);
	        }else{
	        	//如果没有，添加进数据库
	          userDao.insertUser(openid,times,to);
	        }
	        //把用户添加值redis缓存
	        user = userDao.getUserByOpenid(openid);
	        String resul =redisTokenDao.PutUser(to, user);
	        Token token = new Token("200",to);
	        return token;
		}
	}
	
	// 获取openid
	public String getOpenId(String result) {
		int last = result.lastIndexOf('"');
		int second = result.lastIndexOf('"', last - 1);
		return result.substring(second + 1, last);
	}

	//查看获取openid时是否报error
	public String isErrcode(String result){
		int second = result.indexOf('"');
		int last = result.indexOf('"', second + 1);
		return result.substring(second + 1, last);
	}

	public boolean tokenTime(String token) {
		User user = this.getUserByToken(token);
		if(user==null){
			return false;
		}else{
			return true;
		}
	}
}
